package com.example.template.core.dao.impl;
/**
 * Description: //TODO
 * Created by meko on 19-3-15下午5:28
 */


import com.example.template.core.annotation.MapperClass;
import com.example.template.core.dao.BaseDao;
import com.example.template.core.entity.BaseEntity;
import com.example.template.core.dao.CommonMapper;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 *@ClassName BaseDaoImpl
 *@Description TODO
 *@Author meko
 *@Date 19-3-15 下午5:28
 *@Version 1.0
 **/
@Repository("myBatisBaseDao")
public class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    private SqlSession sqlSession;


    @SuppressWarnings("rawtypes")
    public <M extends CommonMapper<T>>M getMapper(Class cls){
        MapperClass mapperClass = (MapperClass) cls.getAnnotation(MapperClass.class);
        if (null == mapperClass){
            throw new RuntimeException("没有注解的MapperClass");
        }
        return (M) getSqlSession().getMapper(mapperClass.value());
    }


    public SqlSession getSqlSession() {
        if (null == sqlSession){
            synchronized (BaseDaoImpl.class){
                this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
            }
        }
        return this.sqlSession;
    }

    @Override
    public T getEntityById(Class<T> cls,Integer id) {

        return this.getMapper(cls).selectByPrimaryKey(id);
    }

    /**
     * TODO 新增实体
     */
    @Override
    public int addEntity(T entity) {
        return this.getMapper(entity.getClass()).insert(entity);
    }

    /**
     * TODO 更新实体
     */
    @Override
    public int updateEntity(T entity) {
        return this.getMapper(entity.getClass()).updateByPrimaryKeySelective(entity);
    }


    @Override
    public List<T> selectAll(Class<T> entityClass,final T entity) {
        return this.getMapper(entityClass).select(entity);
    }

    @Override
    public int deleteEntityById(Class<T> entityClass,Integer id) {
        return this.getMapper(entityClass).deleteByPrimaryKey(id);
    }
}
